package com.wpp.filter;

import com.wpp.core.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.*;

/**
 * @author wpp25
 * @date 2021/5/19 21:12
 * @description：
 */
@Slf4j
@Component
public class BlackListFilter  implements GlobalFilter, Ordered {
    // 模拟黑名单（实际可以去数据库或者redis中查询）
    private static List<String> blackList = new ArrayList<>();

    private static Map<String,Integer> countMap = new HashMap<String,Integer>(){{
        put("0:0:0:0:0:0:0:1",0);
    }};
    static {
        blackList.add("0:0:0:0:0:0:0:1");  // 模拟本机地址
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 思路：获取客户端ip，判断是否在黑名单中，在的话就拒绝访问，不在的话就放行
        // 从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
       /* // 从request对象中获取客户端ip
        String clientIp = request.getRemoteAddress().getHostString();
        // 拿着clientIp去黑名单中查询，存在的话就决绝访问
        Integer ipCount = countMap.get(clientIp);
        if (ipCount == null){
            countMap.put(clientIp,0);
        } else {
            countMap.put(clientIp, ipCount + 1);
        }
//       每三次 就失败1次
        if(ipCount % 3 == 0) {
            // 决绝访问，返回
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            log.debug("=====>IP:" + clientIp + " 在黑名单中，将被拒绝访问！");
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }*/


        if (Objects.nonNull(queryParams.get("token_id")) && !verifyToken(queryParams)) {
            // 决绝访问，返回
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            String data = "token verify fail";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }

    // todo 校验token
    private boolean verifyToken(MultiValueMap<String, String> queryParams) {
        if (Objects.nonNull(queryParams) && JwtUtil.validateJWT(String.valueOf(queryParams.get("token_id"))).isSuccess()) {
         return true;
        }
        return false;
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
